package com.ikun.aimian.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ikun.aimian.common.ErrorCode;
import com.ikun.aimian.exception.ThrowUtils;
import com.ikun.aimian.mapper.JobMapper;
import com.ikun.aimian.model.dto.job.JobQueryRequest;
import com.ikun.aimian.model.entity.Job;
import com.ikun.aimian.model.vo.JobVO;
import com.ikun.aimian.service.JobService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class JobServiceImpl extends ServiceImpl<JobMapper, Job> implements JobService {

    @Override
    public void validJob(Job job, boolean add) {
        ThrowUtils.throwIf(job == null, ErrorCode.PARAMS_ERROR);
        String companyName = job.getCompanyName();
        if (add) {
            ThrowUtils.throwIf(StringUtils.isBlank(companyName), ErrorCode.PARAMS_ERROR, "公司名称不能为空");
        }
        if (companyName != null && companyName.length() > 256) {
            ThrowUtils.throwIf(true, ErrorCode.PARAMS_ERROR, "公司名称过长");
        }
        // 可根据需要增加联系方式等字段的校验
    }

    @Override
    public JobVO getJobVO(Job job, HttpServletRequest request) {
        return JobVO.objToVo(job);
    }

    @Override
    public Page<JobVO> getJobVOPage(Page<Job> jobPage, HttpServletRequest request) {
        List<Job> jobList = jobPage.getRecords();
        Page<JobVO> voPage = new Page<>(jobPage.getCurrent(), jobPage.getSize(), jobPage.getTotal());
        if (jobList == null || jobList.isEmpty()) {
            return voPage;
        }
        List<JobVO> voList = jobList.stream().map(JobVO::objToVo).collect(Collectors.toList());
        voPage.setRecords(voList);
        return voPage;
    }

    @Override
    public QueryWrapper<Job> getQueryWrapper(JobQueryRequest queryRequest) {
        QueryWrapper<Job> queryWrapper = new QueryWrapper<>();
        if (queryRequest == null) {
            return queryWrapper;
        }
        // 模糊查询公司名称
        if (StringUtils.isNotBlank(queryRequest.getCompanyName())) {
            queryWrapper.like("company_name", queryRequest.getCompanyName());
        }
        // 排序
        queryWrapper.orderByDesc("create_time");
        return queryWrapper;
    }
}
